package com.nlx.notes.module.service.impl.loan;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nlx.notes.module.bean.bo.LoanOverviewBO;
import com.nlx.notes.module.bean.bo.LoanSummaryBO;
import com.nlx.notes.module.bean.dto.loan.LoanSummaryQueryDTO;
import com.nlx.notes.module.bean.dto.loan.LoanSummarySaveDTO;
import com.nlx.notes.module.bean.dto.loan.RepayDetailSaveDTO;
import com.nlx.notes.module.core.consts.GlobalConst;
import com.nlx.notes.module.core.enums.error.LoanCodeEnum;
import com.nlx.notes.module.core.util.AmountConverterUtils;
import com.nlx.notes.module.entity.LoanSummary;
import com.nlx.notes.module.mapper.loan.LoanSummaryMapper;
import com.nlx.notes.module.service.loan.ILoanSummaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nlx.notes.support.handler.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author nlx
 * @since 2025-10-25
 */
@Slf4j
@Service
public class LoanSummaryServiceImpl extends ServiceImpl<LoanSummaryMapper, LoanSummary> implements ILoanSummaryService {

    @Override
    public long countByCondition(LoanSummaryQueryDTO loanSummaryQueryDTO) {
        return this.getBaseMapper().countByCondition(loanSummaryQueryDTO);
    }

    @Override
    public List<LoanSummaryBO> pageByCondition(LoanSummaryQueryDTO loanSummaryQueryDTO) {
        return this.getBaseMapper().pageByCondition(loanSummaryQueryDTO);
    }

    @Override
    public LoanSummary findByBorrowerIdAndStatus(Long borrowerId,List<String> status, Long userId) {
        if(null == borrowerId || null == userId){
            return  null;
        }
        return this.getBaseMapper().findByBorrowerIdAndStatus(borrowerId,status,userId);
    }

    @Override
    public LoanSummary saveLoan(LoanSummarySaveDTO loanSummarySaveDTO) {
        LoanSummary loanSummary = new LoanSummary();
        loanSummary.setBorrowerId(loanSummarySaveDTO.getBorrowerId());
        loanSummary.setUserId(loanSummarySaveDTO.getUserId());
        loanSummary.setTotalLoan(loanSummarySaveDTO.getAmountInt());
        loanSummary.setTotalRepay(0);
        loanSummary.setRemainAmount(loanSummarySaveDTO.getAmountInt());
        loanSummary.setLoanStatus(GlobalConst.Loan.LOAN_STATUS_AWAIT_REPAY);
        loanSummary.setLastLoanDate(loanSummarySaveDTO.getLoanDate());
        loanSummary.setCreatedTime(LocalDateTime.now());
        loanSummary.setDelFlag(GlobalConst.DEL_FLAG_NORMAL);
        boolean flag = this.save(loanSummary);
        if(!flag){
            return null;
        }
        return loanSummary;
    }

    @Override
    public boolean incTotalLoan(Integer amount, LocalDate loanDate, Long id) {
        if(null == amount || null == id){
            return false ;
        }
        return this.getBaseMapper().incTotalLoan(amount,loanDate,id);
    }

    @Override
    public void refreshData(Long summaryId, Integer loanTotal, Integer repayTotal) {
        if(null == loanTotal){
            loanTotal = 0;
        }
        if(repayTotal == null){
            repayTotal = 0;
        }
        int remainAmount = loanTotal -  repayTotal;
        LoanSummary loanSummary = new LoanSummary();
        loanSummary.setId(summaryId);
        loanSummary.setTotalLoan(loanTotal);
        loanSummary.setTotalRepay(repayTotal);
        loanSummary.setRemainAmount(remainAmount);
        if(remainAmount == 0){
            loanSummary.setLoanStatus(GlobalConst.Loan.LOAN_STATUS_SETTLE);
        }else if(remainAmount == loanTotal){
            loanSummary.setLoanStatus(GlobalConst.Loan.LOAN_STATUS_AWAIT_REPAY);
        }else{
            loanSummary.setLoanStatus(GlobalConst.Loan.LOAN_STATUS_ONGOING);
        }
        loanSummary.setUpdatedTime(LocalDateTime.now());
        this.updateById(loanSummary);
    }

    @Override
    public LoanOverviewBO sumLoan(LoanSummaryQueryDTO loanSummaryQueryDTO) {

        return this.getBaseMapper().sumLoan(loanSummaryQueryDTO);
    }

    @Override
    public LoanSummary findAndCheckById(Long id, Long userId) {
        if(null == id || null == userId){
            log.error("没有id或者用户id");
            throw new BusinessException(LoanCodeEnum.DATA_NOT_EXISTS_ERROR);
        }
        LoanSummary loanSummary = this.getBaseMapper().selectOne(Wrappers.lambdaQuery(LoanSummary.class)
                .eq(LoanSummary::getId, id).eq(LoanSummary::getUserId, userId)
                .eq(LoanSummary::getDelFlag, GlobalConst.DEL_FLAG_NORMAL), false);
        if(null == loanSummary){
            log.error("数据 {} 不存在或者不属于当前用户 {} ",id,userId);
            throw new BusinessException(LoanCodeEnum.DATA_NOT_EXISTS_ERROR);
        }
        return loanSummary;

    }

    @Override
    public boolean saveRepay(RepayDetailSaveDTO repayDetailSaveDTO) {
        LoanSummary loanSummary = this.findAndCheckById(repayDetailSaveDTO.getLoanSummaryId(),repayDetailSaveDTO.getUserId());
        int repayAmount = AmountConverterUtils.convertYuanToFen(repayDetailSaveDTO.getRepayAmount());
        if(repayAmount >= loanSummary.getRemainAmount()){
            log.info("已还清");
            repayDetailSaveDTO.setLoanStatus(GlobalConst.Loan.LOAN_STATUS_SETTLE);
        }else{
            repayDetailSaveDTO.setLoanStatus(GlobalConst.Loan.LOAN_STATUS_ONGOING);
        }
        repayDetailSaveDTO.setRepayAmountInt(repayAmount);
        return this.getBaseMapper().saveRepay(repayDetailSaveDTO);
    }


}
